package com.dinglian.ots.common;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @author wangbo
 */
public class ToolUtils {


    /**
     * 将boolean值转成数字存入数据库
     *
     * @param result
     * @return
     */
    public static Byte getByteByBoolean(boolean result) {
        if (result) {
            return Byte.valueOf("1");
        } else {
            return Byte.valueOf("0");
        }
    }

    /**
     * 生成验证码
     *
     * @param num
     * @return
     */
    public static String createCode(int num) {
        String vcode = "";
        Random random = new Random();
        for (int i = 0; i < num; i++) {
            vcode += random.nextInt(10);
        }
        return vcode;
    }


    /**
     * 上传图片
     *
     * @param url           根目录
     * @param userName      一级文件夹 用户名
     * @param childFileName 二级文件夹
     * @param file          文件
     * @return
     */
    public static String uploadPicture(String url, String userName, String childFileName, MultipartFile file) {
        String filePath = childFileName + userName + "/";
        String path = url + filePath;
        String name = file.getOriginalFilename();
//        String suffix = name.substring(name.lastIndexOf("."));
        String suffix = ".jpg";
        //生成文件ID名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        String result = "";
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            result += random.nextInt(10);
        }
        String fileId = newDate + result;

        File f = new File(path);
        if (!f.exists()) {
            f.mkdirs();
        }
        compressPic(file,path+fileId);
       /* //组合文件名
        String fileName = fileId + suffix;
        File f = new File(path);
        if (!f.exists()) {
            f.mkdirs();
        }
        path = path + fileName;
        f = new File(path);
        try {
            file.transferTo(f);
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        return filePath + fileId+suffix;
    }


    /**
     * 上传图片
     *
     * @param url           根目录
     * @param userName      一级文件夹 用户名
     * @param childFileName 二级文件夹
     * @param file          文件
     * @return
     */
    public static String uploadFile(String url, String userName, String childFileName, MultipartFile file) {
        String filePath = childFileName + userName + "/";
        String path = url + filePath;
        String name = file.getOriginalFilename();
        String suffix = name.substring(name.lastIndexOf("."));
//        String suffix = ".jpg";
        //生成文件ID名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        String result = "";
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            result += random.nextInt(10);
        }
        String fileId = newDate + result;

        //组合文件名
        String fileName = fileId + suffix;
        File f = new File(path);
        if (!f.exists()) {
            f.mkdirs();
        }
        path = path + fileName;
        f = new File(path);
        try {
            file.transferTo(f);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath + fileName;
    }

    /**
     * 判断是否为中文字符
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    /**
     * Unicode转中文
     *
     * @param unicode
     * @return
     */
    public static String decodeUnicode(final String unicode) {
        StringBuffer string = new StringBuffer();

        String[] hex = unicode.split("\\\\u");

        for (int i = 0; i < hex.length; i++) {

            try {
                // 汉字范围 \u4e00-\u9fa5 (中文)
                if (hex[i].length() >= 4) {//取前四个，判断是否是汉字
                    String chinese = hex[i].substring(0, 4);
                    try {
                        int chr = Integer.parseInt(chinese, 16);
                        boolean isChinese = isChinese((char) chr);
                        //转化成功，判断是否在  汉字范围内
                        if (isChinese) {//在汉字范围内
                            // 追加成string
                            string.append((char) chr);
                            //并且追加  后面的字符
                            String behindString = hex[i].substring(4);
                            string.append(behindString);
                        } else {
                            string.append(hex[i]);
                        }
                    } catch (NumberFormatException e1) {
                        string.append(hex[i]);
                    }

                } else {
                    string.append(hex[i]);
                }
            } catch (NumberFormatException e) {
                string.append(hex[i]);
            }
        }

        return string.toString();
    }


    /**
     * 生成订单编号
     *
     * @return String
     * @author WangBo
     * @date 2018年8月1日下午1:38:24
     */
    public static String createOrderNo(String type) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        String result = "";
        Random random = new Random();
        for (int i = 0; i < 3; i++) {
            result += random.nextInt(10);
        }
        return type + newDate + result;
    }

    /**
     * 获取当前sku版本号并加1
     *
     * @param version
     * @return
     */
    public static String getVersion(String version) {
        int version1 = version.indexOf("n");
        int version2 = version.indexOf(".");
        String number = version.substring(version1 + 1, version2);
        String newVersion = "version" + (Integer.valueOf(number) + 1) + ".0";
        return newVersion;
    }

    /**
     * 单位转换为分
     *
     * @param money
     * @return
     */
    public static Integer yuanToCent(String money) {
        BigDecimal bigDecimal = new BigDecimal(money);
        BigDecimal m = bigDecimal.multiply(new BigDecimal(100));
        return m.intValue();
    }


    public static String objectToString(Object object) {
        if (object != null) {
            return object.toString();
        } else {
            return null;
        }
    }

    /**
     * 解码
     * @param str
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String urlDecoder(String str) {
        if (str == null){
            str = "";
        }
        String result ="";
        try {
            result =  URLDecoder.decode(str,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 压缩图片
     */
    public static void compressPic(MultipartFile file ,String path){
        try {
            Thumbnails.of(file.getInputStream())
                    .scale(1f)
                    .outputQuality(0.25f)
                    .outputFormat("jpg")
                    .toFile(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
